#include <iostream>
#include <algorithm>
#include <fstream>
#include "Master.h"

using namespace std;

void Master::sendAllObs(const string &rep, const string &roomname, const string &type)
{
	for(vector<obs>::iterator it = obss.begin(); it != obss.end(); ++it)
	{
		if(it->roomname == roomname)
		{
			string proto = "ETUD/OBS/REP/"+type;
			sendProto(proto.c_str(), &it->sock);
			it->sock.send4(rep.size());
			it->sock.sendMsg(rep.c_str(), rep.size());
		}
	}
}

bool readActivity(vector<string> &questions, string filename, string &type)
{
	ifstream file(filename.c_str(), ios::in);
 
	if(file)
	{
		string word, line;
		file >> type;
		while(!file.eof())
		{
			getline(file, word);
			questions.push_back(word);
			if(word == "QUESTION" || word == "REPONSE")
			{
				getline(file, line);
				questions.push_back(line);
			}
		}

		file.close();
		return true;
	}
	else
		return false;
}

void *Master::manageEtu(void *arg)
{
	void **param = (void**)(arg);
	Master *m = (Master*)(param[0]);
	etu *e = (etu*)(param[1]);
	
	// par défaut, on lance l'activité
	e->isAssistant = false;
	
	int status = 0;
	string msg = "", buf = "";
	long size = 0;
	
	cout << "Un nouvel etudiant est en ligne : " << e->login << endl;
	char p = m->proto["ETUD/LISTE"];
	e->sock.sendMsg((void*)(&p), 1);
	size = m->rooms.size();
	e->sock.send4(size);
	roomIter it, itEnd = m->rooms.end();
	for(it = m->rooms.begin(); it != itEnd; ++it)
	{
		e->sock.send4(it->name.size());
		e->sock.sendMsg(it->name.c_str(), it->name.size());
	}
	
	status = m->getProto(msg, &e->sock);
	if(status > 0 && msg == "ETUD/CHOIX/SALLE")
	{
		e->sock.read4(&size);
		status = m->getString(e->roomname, size, &e->sock);
		
		if(status > 0 && !m->checkRoom(e->roomname))
			m->sendProto("ETUD/ERR/CHOIXSALLE", &e->sock);
		else if(status > 0)
		{
			m->sendProto("ETUD/OK/CHOIXSALLE", &e->sock);
			cout<<e->login<<" est dans la salle : "<<e->roomname<<endl;
		}
	}
	else
	{
		cout << "Deconnexion de " << e->login << endl;
		return NULL;
	}

	bool findrr = false;
	room r;
	for(it = m->rooms.begin(); it != itEnd && !findrr; ++it)
	  {
	    if(e->roomname == it->name)
	      {
		r = (*it);
		findrr = true;
	      }
	  }
	vector<string>::iterator it2, it2End;

	e->sock.send4(r.activities.size());

	for(it2 = r.activities.begin(); it2 != r.activities.end(); ++it2)
	{
		e->sock.send4((*it2).size());
		e->sock.sendMsg((*it2).c_str(), (*it2).size());
	}	
	
	status = m->getProto(buf, &e->sock);
	if (status <= 0 || buf != "ETUD/CHOIX/ACTIVITE")
		return NULL;
		
	string act = "";
	long str_size = 0;
	
	status = e->sock.read4(&str_size);
	status = m->getString(act, str_size, &e->sock);
	bool findact = false;
	for(it2 = r.activities.begin(); it2 != r.activities.end() && !findact; ++it2)
	{
		if (act == (*it2))
			findact = true;
	}
	
	if (findact == false)
	  {
		  m->sendProto("ETUD/ERR/CHOIXACTIVITE", &e->sock);
		  return NULL;
	  }

	m->sendProto("ETUD/OK/CHOIXACTIVITE", &e->sock);
	
	//////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////
	// On ouvre le fichier act
	// si erreur, pas de questions, on déconnecte
	vector<string> questions;
	string type;
	act = "activities/" + act;
	if(!readActivity(questions, act, type) || questions.size() == 0)
	{
		cout << "Erreur au chargement de l'activite, deconnexion de " << e->login << endl;
		return NULL;
	}
	buf = "";
	if(type == "QCM")
	{
		int nbR;
		while(buf != "ETUD/LOGOUT" && status > 0)
		{
			int cpt = 0;
			while(cpt < questions.size() && questions[cpt] != "FIN" && status > 0)
			{
				nbR = 0;
				pthread_mutex_lock(&e->writing);
				if(!e->isAssistant)
				{
					m->sendProto("ETU/QCM", &e->sock);
					for(int i=cpt; i<questions.size(); i++)
					{
						if(questions[i] == "REPONSE")
							nbR++;
					}
					e->sock.send4(questions[cpt].size());
					e->sock.sendMsg(questions[cpt].c_str(), questions[cpt].size());
					cpt+=2;
					e->sock.send4(nbR+1);
					for(int i=0; i<=nbR; i++)
					{
						e->sock.send4(questions[cpt].size());
						e->sock.sendMsg(questions[cpt].c_str(), questions[cpt].size());
						cpt+=2;
					}
					cpt--;
					////////////////////////////////////////////////////////////////////
					// ATTENTE DE LA REPONSE
					////////////////////////////////////////////////////////////////////
						long size_r;
						string r = "";
						e->sock.read4(&size_r);
						m->getString(r, size_r, &e->sock);
						m->sendAllObs(r, e->roomname, "QCM");
				}
				pthread_mutex_unlock(&e->writing);
			}
		}
	}
	else if(type == "QUESTIONS")
	{
	}
	cout << "Deconnexion de l'etudiant " << e->login << endl;
}
